import 'package:flutter/material.dart';
import '../models/mood_record.dart';
import '../models/mood.dart';
import '../constants/app_theme.dart';
import '../constants/app_constants.dart';

/// 筛选选项数据类
class FilterOptions {
  /// 日期范围
  DateTimeRange? dateRange;
  
  /// 选中的情绪类型
  List<MoodType> selectedMoods;
  
  /// 强度范围
  RangeValues? intensityRange;
  
  /// 选中的标签
  List<String> selectedTags;
  
  /// 天气条件
  List<String> selectedWeather;
  
  /// 是否包含媒体
  bool? hasMedia;
  
  /// 最小内容长度
  int? minContentLength;
  
  /// 排序方式
  SortOption sortOption;
  
  /// 排序顺序
  bool ascending;

  FilterOptions({
    this.dateRange,
    this.selectedMoods = const [],
    this.intensityRange,
    this.selectedTags = const [],
    this.selectedWeather = const [],
    this.hasMedia,
    this.minContentLength,
    this.sortOption = SortOption.date,
    this.ascending = false,
  });

  /// 复制并修改
  FilterOptions copyWith({
    DateTimeRange? dateRange,
    List<MoodType>? selectedMoods,
    RangeValues? intensityRange,
    List<String>? selectedTags,
    List<String>? selectedWeather,
    bool? hasMedia,
    int? minContentLength,
    SortOption? sortOption,
    bool? ascending,
  }) {
    return FilterOptions(
      dateRange: dateRange ?? this.dateRange,
      selectedMoods: selectedMoods ?? this.selectedMoods,
      intensityRange: intensityRange ?? this.intensityRange,
      selectedTags: selectedTags ?? this.selectedTags,
      selectedWeather: selectedWeather ?? this.selectedWeather,
      hasMedia: hasMedia ?? this.hasMedia,
      minContentLength: minContentLength ?? this.minContentLength,
      sortOption: sortOption ?? this.sortOption,
      ascending: ascending ?? this.ascending,
    );
  }

  /// 检查是否有活动的筛选条件
  bool get hasActiveFilters {
    return dateRange != null ||
           selectedMoods.isNotEmpty ||
           intensityRange != null ||
           selectedTags.isNotEmpty ||
           selectedWeather.isNotEmpty ||
           hasMedia != null ||
           minContentLength != null;
  }

  /// 重置所有筛选条件
  FilterOptions reset() {
    return FilterOptions(
      sortOption: sortOption,
      ascending: ascending,
    );
  }
}

/// 排序选项
enum SortOption {
  date,
  intensity,
  mood,
  contentLength,
}

/// 筛选组件
class FilterWidget extends StatefulWidget {
  /// 当前筛选选项
  final FilterOptions filterOptions;
  
  /// 筛选选项变化回调
  final Function(FilterOptions options) onFilterChanged;
  
  /// 可用的标签列表
  final List<String> availableTags;
  
  /// 是否显示高级选项
  final bool showAdvancedOptions;

  const FilterWidget({
    super.key,
    required this.filterOptions,
    required this.onFilterChanged,
    this.availableTags = const [],
    this.showAdvancedOptions = true,
  });

  @override
  State<FilterWidget> createState() => _FilterWidgetState();
}

class _FilterWidgetState extends State<FilterWidget> {
  late FilterOptions _currentOptions;
  bool _showAdvanced = false;

  @override
  void initState() {
    super.initState();
    _currentOptions = widget.filterOptions;
  }

  /// 更新筛选选项
  void _updateOptions(FilterOptions newOptions) {
    setState(() {
      _currentOptions = newOptions;
    });
    widget.onFilterChanged(newOptions);
  }

  /// 重置筛选条件
  void _resetFilters() {
    _updateOptions(_currentOptions.reset());
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: AppTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(),
          const SizedBox(height: 16),
          _buildDateRangeFilter(),
          const SizedBox(height: 16),
          _buildMoodFilter(),
          const SizedBox(height: 16),
          _buildIntensityFilter(),
          if (_showAdvanced && widget.showAdvancedOptions) ...[
            const SizedBox(height: 16),
            _buildTagFilter(),
            const SizedBox(height: 16),
            _buildWeatherFilter(),
            const SizedBox(height: 16),
            _buildMediaFilter(),
            const SizedBox(height: 16),
            _buildContentLengthFilter(),
          ],
          const SizedBox(height: 16),
          _buildSortOptions(),
          const SizedBox(height: 16),
          _buildActionButtons(),
        ],
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          '筛选条件',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        Row(
          children: [
            if (_currentOptions.hasActiveFilters)
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 8,
                  vertical: 4,
                ),
                decoration: BoxDecoration(
                  color: AppTheme.primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  '已筛选',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppTheme.primaryColor,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            if (widget.showAdvancedOptions) ...[
              const SizedBox(width: 8),
              TextButton(
                onPressed: () {
                  setState(() {
                    _showAdvanced = !_showAdvanced;
                  });
                },
                child: Text(
                  _showAdvanced ? '收起' : '高级',
                  style: TextStyle(
                    color: AppTheme.primaryColor,
                  ),
                ),
              ),
            ],
          ],
        ),
      ],
    );
  }

  /// 构建日期范围筛选
  Widget _buildDateRangeFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '日期范围',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: _buildQuickDateButton('今天', () {
                final now = DateTime.now();
                final today = DateTime(now.year, now.month, now.day);
                _updateOptions(_currentOptions.copyWith(
                  dateRange: DateTimeRange(
                    start: today,
                    end: today.add(const Duration(days: 1)),
                  ),
                ));
              }),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildQuickDateButton('本周', () {
                final now = DateTime.now();
                final weekStart = now.subtract(Duration(days: now.weekday - 1));
                final weekEnd = weekStart.add(const Duration(days: 6));
                _updateOptions(_currentOptions.copyWith(
                  dateRange: DateTimeRange(
                    start: DateTime(weekStart.year, weekStart.month, weekStart.day),
                    end: DateTime(weekEnd.year, weekEnd.month, weekEnd.day),
                  ),
                ));
              }),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: _buildQuickDateButton('本月', () {
                final now = DateTime.now();
                final monthStart = DateTime(now.year, now.month, 1);
                final monthEnd = DateTime(now.year, now.month + 1, 0);
                _updateOptions(_currentOptions.copyWith(
                  dateRange: DateTimeRange(
                    start: monthStart,
                    end: monthEnd,
                  ),
                ));
              }),
            ),
          ],
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: _showDateRangePicker,
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              border: Border.all(color: AppTheme.dividerColor),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.date_range,
                  color: AppTheme.textSecondaryColor,
                  size: 20,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    _currentOptions.dateRange != null
                        ? '${_formatDate(_currentOptions.dateRange!.start)} - ${_formatDate(_currentOptions.dateRange!.end)}'
                        : '选择日期范围',
                    style: TextStyle(
                      color: _currentOptions.dateRange != null
                          ? AppTheme.textPrimaryColor
                          : AppTheme.textSecondaryColor,
                    ),
                  ),
                ),
                if (_currentOptions.dateRange != null)
                  GestureDetector(
                    onTap: () {
                      _updateOptions(_currentOptions.copyWith(
                        dateRange: null,
                      ));
                    },
                    child: Icon(
                      Icons.clear,
                      color: AppTheme.textSecondaryColor,
                      size: 20,
                    ),
                  ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建快速日期按钮
  Widget _buildQuickDateButton(String label, VoidCallback onPressed) {
    return OutlinedButton(
      onPressed: onPressed,
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 8),
        side: BorderSide(color: AppTheme.dividerColor),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          color: AppTheme.textPrimaryColor,
        ),
      ),
    );
  }

  /// 构建情绪筛选
  Widget _buildMoodFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '情绪类型',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: MoodType.values.map((mood) {
            final isSelected = _currentOptions.selectedMoods.contains(mood);
            return FilterChip(
              label: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    mood.emoji,
                    style: const TextStyle(fontSize: 16),
                  ),
                  const SizedBox(width: 4),
                  Text(
                    mood.name,
                    style: const TextStyle(fontSize: 12),
                  ),
                ],
              ),
              selected: isSelected,
              onSelected: (selected) {
                final newMoods = List<MoodType>.from(_currentOptions.selectedMoods);
                if (selected) {
                  newMoods.add(mood);
                } else {
                  newMoods.remove(mood);
                }
                _updateOptions(_currentOptions.copyWith(
                  selectedMoods: newMoods,
                ));
              },
              selectedColor: mood.color.withOpacity(0.2),
              checkmarkColor: mood.color,
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建强度筛选
  Widget _buildIntensityFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '强度范围',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        RangeSlider(
          values: _currentOptions.intensityRange ?? const RangeValues(1, 10),
          min: 1,
          max: 10,
          divisions: 9,
          labels: RangeLabels(
            '${(_currentOptions.intensityRange?.start ?? 1).round()}',
            '${(_currentOptions.intensityRange?.end ?? 10).round()}',
          ),
          onChanged: (values) {
            _updateOptions(_currentOptions.copyWith(
              intensityRange: values,
            ));
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '低强度',
              style: TextStyle(
                fontSize: 12,
                color: AppTheme.textSecondaryColor,
              ),
            ),
            Text(
              '高强度',
              style: TextStyle(
                fontSize: 12,
                color: AppTheme.textSecondaryColor,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建标签筛选
  Widget _buildTagFilter() {
    if (widget.availableTags.isEmpty) {
      return const SizedBox.shrink();
    }
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '标签',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: widget.availableTags.map((tag) {
            final isSelected = _currentOptions.selectedTags.contains(tag);
            return FilterChip(
              label: Text(
                tag,
                style: const TextStyle(fontSize: 12),
              ),
              selected: isSelected,
              onSelected: (selected) {
                final newTags = List<String>.from(_currentOptions.selectedTags);
                if (selected) {
                  newTags.add(tag);
                } else {
                  newTags.remove(tag);
                }
                _updateOptions(_currentOptions.copyWith(
                  selectedTags: newTags,
                ));
              },
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建天气筛选
  Widget _buildWeatherFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '天气条件',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: AppConstants.weatherOptions.map((weather) {
            final isSelected = _currentOptions.selectedWeather.contains(weather);
            return FilterChip(
              label: Text(
                weather,
                style: const TextStyle(fontSize: 12),
              ),
              selected: isSelected,
              onSelected: (selected) {
                final newWeather = List<String>.from(_currentOptions.selectedWeather);
                if (selected) {
                  newWeather.add(weather);
                } else {
                  newWeather.remove(weather);
                }
                _updateOptions(_currentOptions.copyWith(
                  selectedWeather: newWeather,
                ));
              },
            );
          }).toList(),
        ),
      ],
    );
  }

  /// 构建媒体筛选
  Widget _buildMediaFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '媒体内容',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: RadioListTile<bool?>(
                title: const Text('全部', style: TextStyle(fontSize: 12)),
                value: null,
                groupValue: _currentOptions.hasMedia,
                onChanged: (value) {
                  _updateOptions(_currentOptions.copyWith(
                    hasMedia: value,
                  ));
                },
                dense: true,
                contentPadding: EdgeInsets.zero,
              ),
            ),
            Expanded(
              child: RadioListTile<bool?>(
                title: const Text('有媒体', style: TextStyle(fontSize: 12)),
                value: true,
                groupValue: _currentOptions.hasMedia,
                onChanged: (value) {
                  _updateOptions(_currentOptions.copyWith(
                    hasMedia: value,
                  ));
                },
                dense: true,
                contentPadding: EdgeInsets.zero,
              ),
            ),
            Expanded(
              child: RadioListTile<bool?>(
                title: const Text('无媒体', style: TextStyle(fontSize: 12)),
                value: false,
                groupValue: _currentOptions.hasMedia,
                onChanged: (value) {
                  _updateOptions(_currentOptions.copyWith(
                    hasMedia: value,
                  ));
                },
                dense: true,
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建内容长度筛选
  Widget _buildContentLengthFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '最小内容长度',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Slider(
          value: (_currentOptions.minContentLength ?? 0).toDouble(),
          min: 0,
          max: 500,
          divisions: 10,
          label: '${_currentOptions.minContentLength ?? 0} 字符',
          onChanged: (value) {
            _updateOptions(_currentOptions.copyWith(
              minContentLength: value.toInt(),
            ));
          },
        ),
      ],
    );
  }

  /// 构建排序选项
  Widget _buildSortOptions() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '排序方式',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: DropdownButtonFormField<SortOption>(
                value: _currentOptions.sortOption,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 8,
                  ),
                ),
                items: const [
                  DropdownMenuItem(
                    value: SortOption.date,
                    child: Text('日期', style: TextStyle(fontSize: 12)),
                  ),
                  DropdownMenuItem(
                    value: SortOption.intensity,
                    child: Text('强度', style: TextStyle(fontSize: 12)),
                  ),
                  DropdownMenuItem(
                    value: SortOption.mood,
                    child: Text('情绪', style: TextStyle(fontSize: 12)),
                  ),
                  DropdownMenuItem(
                    value: SortOption.contentLength,
                    child: Text('内容长度', style: TextStyle(fontSize: 12)),
                  ),
                ],
                onChanged: (value) {
                  if (value != null) {
                    _updateOptions(_currentOptions.copyWith(
                      sortOption: value,
                    ));
                  }
                },
              ),
            ),
            const SizedBox(width: 8),
            IconButton(
              onPressed: () {
                _updateOptions(_currentOptions.copyWith(
                  ascending: !_currentOptions.ascending,
                ));
              },
              icon: Icon(
                _currentOptions.ascending
                    ? Icons.arrow_upward
                    : Icons.arrow_downward,
              ),
              tooltip: _currentOptions.ascending ? '升序' : '降序',
            ),
          ],
        ),
      ],
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: OutlinedButton(
            onPressed: _currentOptions.hasActiveFilters ? _resetFilters : null,
            child: const Text('重置'),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              foregroundColor: Colors.white,
            ),
            child: const Text('应用'),
          ),
        ),
      ],
    );
  }

  /// 显示日期范围选择器
  Future<void> _showDateRangePicker() async {
    final dateRange = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDateRange: _currentOptions.dateRange,
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: AppTheme.primaryColor,
            ),
          ),
          child: child!,
        );
      },
    );
    
    if (dateRange != null) {
      _updateOptions(_currentOptions.copyWith(
        dateRange: dateRange,
      ));
    }
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}/${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')}';
  }
}

/// 筛选结果应用器
class FilterApplier {
  /// 应用筛选条件到记录列表
  static List<MoodRecord> applyFilters(
    List<MoodRecord> records,
    FilterOptions options,
  ) {
    List<MoodRecord> filteredRecords = List.from(records);
    
    // 日期范围筛选
    if (options.dateRange != null) {
      filteredRecords = filteredRecords.where((record) {
        return record.createdAt.isAfter(options.dateRange!.start) &&
               record.createdAt.isBefore(options.dateRange!.end.add(const Duration(days: 1)));
      }).toList();
    }
    
    // 情绪类型筛选
    if (options.selectedMoods.isNotEmpty) {
      filteredRecords = filteredRecords.where((record) {
        return options.selectedMoods.contains(record.moodType);
      }).toList();
    }
    
    // 强度范围筛选
    if (options.intensityRange != null) {
      filteredRecords = filteredRecords.where((record) {
        return record.intensity >= options.intensityRange!.start &&
               record.intensity <= options.intensityRange!.end;
      }).toList();
    }
    
    // 标签筛选
    if (options.selectedTags.isNotEmpty) {
      filteredRecords = filteredRecords.where((record) {
        return options.selectedTags.any((tag) => record.tags.contains(tag));
      }).toList();
    }
    
    // 天气筛选
    if (options.selectedWeather.isNotEmpty) {
      filteredRecords = filteredRecords.where((record) {
        return record.weather != null &&
               options.selectedWeather.contains(record.weather);
      }).toList();
    }
    
    // 媒体筛选
    if (options.hasMedia != null) {
      filteredRecords = filteredRecords.where((record) {
        final hasMedia = record.mediaAttachments.isNotEmpty;
        return hasMedia == options.hasMedia;
      }).toList();
    }
    
    // 内容长度筛选
    if (options.minContentLength != null && options.minContentLength! > 0) {
      filteredRecords = filteredRecords.where((record) {
        return (record.diaryContent?.length ?? 0) >= options.minContentLength!;
      }).toList();
    }
    
    // 排序
    filteredRecords.sort((a, b) {
      int comparison;
      
      switch (options.sortOption) {
        case SortOption.date:
          comparison = a.createdAt.compareTo(b.createdAt);
          break;
        case SortOption.intensity:
          comparison = a.intensity.compareTo(b.intensity);
          break;
        case SortOption.mood:
          comparison = a.moodType.index.compareTo(b.moodType.index);
          break;
        case SortOption.contentLength:
          comparison = (a.diaryContent?.length ?? 0).compareTo(b.diaryContent?.length ?? 0);
          break;
      }
      
      return options.ascending ? comparison : -comparison;
    });
    
    return filteredRecords;
  }
}